package blog.web.utils;

import com.google.common.reflect.TypeToken;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Created by zzl on 2016-05-11.
 */
public class JsonUtils {

    private static final Gson gsonParse;
    private static final Gson gsonStringify;
    private static final Gson gsonStringify_;

    static {
        try {
            FieldNamingPolicy namingPolicy = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES;
            gsonParse = new GsonBuilder().setFieldNamingPolicy(namingPolicy).create();

            gsonStringify = new Gson();
            //添加disableHtmlEscaping()解决自动转码
            gsonStringify_ = new GsonBuilder().setFieldNamingPolicy(namingPolicy).disableHtmlEscaping().create();
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static <T> T parse(String json, Class<T> classOfT) {
        return gsonParse.fromJson(json, classOfT);
    }

    public static String stringify(Object bean) {
        String json = gsonStringify.toJson(bean);
        return json;
    }

    public static String stringify_(Object bean) {
        String json = gsonStringify_.toJson(bean);
        return json;
    }

    public static Map<String, Object> parseMap(String json) {
        Type type = new TypeToken<Map<String, Object>>(){}.getType();
        return gsonParse.fromJson(json, type);
    }
}
